%% Part I

% Set Paths for local folders - Valerie (NOTE: comment out this code to
% include your own, please)
FOLDER_PATH = 'C:\Users\vsimonis\Documents\MATLAB\LocalNematodes\';
VIDEO_PATH = 'C:\Users\vsimonis\Documents\MATLAB\NematodesMedia\';
MM_PATH = 'C:\Users\vsimonis\Documents\MATLAB\LocalNematodes\mmread\';

%% add paths for local folder, video location and mmread (library) location
addpath(FOLDER_PATH, VIDEO_PATH, MM_PATH);

%% Specify video to read in
fName = 'SM1.avi';

%% Codec issues work around to read video into matlab
% due to Codec issues, do mmread in (available from Mathworks)
tempVidIn = mmread(sprintf('%s%s', VIDEO_PATH,fName));
% write temp video out
tempVidOut = VideoWriter(sprintf('%s%s%s',VIDEO_PATH, 'Out', fName));
% Open stream to actually write the video to disk 
open(tempVidOut);
% Write video to disk
tempVidOut.writeVideo(tempVidIn.frames);
% Close stream 
close(tempVidOut);
clear tempVidOut
%% Actually Read in File
wormVid = VideoReader(sprintf('%s%s', 'Out', fName));

%% Get frame data in 4-D struct 
% I assume the object will have the video stored in a 4-D matrix with row, col, intensity, frame number).
allFrames = read(wormVid);

for i = 1:size(allFrames,4)
    framesFromVideo(:,:,i) = rgb2gray(allFrames(:,:,:,i));
end

% %% Get Properties
% %frame rate, height, width, number of frames, format 
% props = get(wormVid);
% 
% %% Frame Play - perform ops on frames
% % Convince yourself that you can programmatically read an individual frame by using imshow.
% showFrame(allFrames, 30);
% 
% % Figure out how to play back the video to screen from the object.
% implay(allFrames);

% Do a simple experiment of selecting a sequence of frames to play back, perhaps - undersampling by selecting every other frame to play back. 
%{
for i = 1:props.NumberOfFrames
    if mod(i,2) == 0
        newMovie(:,:,:,i) = allFrames(:,:,:,i);
    end
end
%}
% implay(newMovie);

 
%% Part II -  Reducing data
 
% If you can find a video that is not in 8 bit grayscale format, convert it to 8 bit grayscale after reading in the video. 
% Use our existing code to threshold the image and extract the centroid using regionprops function. 
% Draw a box around the centroid with a reasonable aspect ratio that will contain any reasonably sized worm in any orientation and posture.  Perhaps, use imcrop.  Convince yourself that the code works if the box size extends off the existing video frame. 
% Create an 8 bit video with the new frame size .
% Create a n x 2 matrix with a list of coordinates for the new frame position reference ( I think for the imcrop function requires the upper left corner of the box as a reference, so this is what should probably be stored.

%clear frame props wormVid